package org.example;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

/**
 * @author zhangxv
 */
public class SocketClientTest {
    public static void main(String[] args) throws IOException, TransformerException, ParserConfigurationException {
        System.out.println("client.........");
        Socket socket = null;
        InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
        int serverPort = 9999;
        //测试主机是否在线(Windows XP不适用)
        if (inetAddress.isReachable(5000)) {
            socket = new Socket(inetAddress, serverPort);

            //封装数据写给服务器端
            OutputStream outputStream = socket.getOutputStream();
            DataOutputStream dataOutputStream = new DataOutputStream(outputStream);

            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = factory.newDocumentBuilder();
            Document document = documentBuilder.newDocument();
            document.setXmlStandalone(true);
            Element parent = document.createElement("packet");
            document.appendChild(parent);

            Element SYS_ID = document.createElement("SYS_ID");
            SYS_ID.appendChild(document.createTextNode("ZFB2C"));
            Element TRANS_CODE = document.createElement("TRANS_CODE");
            TRANS_CODE.appendChild(document.createTextNode("TOKEN"));
            Element ACCESS_TOKEN = document.createElement("ACCESS_TOKEN");
            ACCESS_TOKEN.appendChild(document.createTextNode("skdlajtfoiewjflkdsajflkdsajlkfdsajfljdsalkf"));
            Element RET_CODE = document.createElement("RET_CODE");
            RET_CODE.appendChild(document.createTextNode("0000"));
            Element RET_RMK = document.createElement("RET_RMK");
            RET_RMK.appendChild(document.createTextNode("交易成功"));
            parent.appendChild(SYS_ID);
            parent.appendChild(TRANS_CODE);
            parent.appendChild(ACCESS_TOKEN);
            parent.appendChild(RET_CODE);
            parent.appendChild(RET_RMK);

            System.out.println(document);
            //转换xml
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();

            DOMSource source = new DOMSource(document);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            transformer.transform(source, new StreamResult(bos));
            String result = bos.toString();

            System.out.println(result);

            //写数据
            dataOutputStream.writeUTF(result);
            //  socket.shutdownOutput();
            // 4.获取输入流，并读取服务器端的响应信息
            // 4.关闭资源
            //读
            InputStream is = socket.getInputStream();
            DataInputStream in = new DataInputStream(is);
            String data = in.readUTF();
            DOM(data);
            in.close();
            is.close();
            bos.close();
            dataOutputStream.flush();
            dataOutputStream.close();
            socket.close();
        }
    }

    //dom解析
    public static void DOM(String data) {
        try {
            //遍历xml获取内容
            byte[] b = data.getBytes();
            InputStream inp = new ByteArrayInputStream(b);
            DocumentBuilderFactory factory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(inp);
//            NodeList nl = doc.getElementsByTagName("packet");
//			System.out.println(nl.getLength());
//            for (int i = 0; i < nl.getLength(); i++) {
            System.out.println("RET_CODE:  "
                    + doc.getElementsByTagName("RET_CODE").item(0)
                    .getFirstChild().getNodeValue());
            System.out.println("RET_RMK:  "
                    + doc.getElementsByTagName("RET_RMK").item(0)
                    .getFirstChild().getNodeValue());
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
